<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

\think\Loader::addNamespace('beecloud\rest','../vendor/beecloud.cn/rest/');

// 应用公共文件

// api请求正确返回
function api_return($info,$data){
    $result = array(
        'code' => 1,
        'info' => $info,
        'data' => $data
    );
    return json($result);
}

// api请求错误返回
function api_error($error,$info)
{
    $result = array(
        'code' => 0,
        'error' => $error,
        'info' => $info
    );
    return json($result);
}

/**
 * 封装CURL请求函数
 * @param $url 请求地址
 * @param array $header 请求头[HTTP Request headers  例如 ['App-Key:'.$app_key,]
 * @param array $data 参数
 * @return mixed|SimpleXMLElement
 */
function doCurl($url,$header = null,$data = null){
    if(empty($url)){
        return false;
    }
    $curl = curl_init();
    if(is_array($header)){
        curl_setopt($curl,CURLOPT_HEADER,$header);
    }
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if(!empty($data)){
        curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
    }
    $outPut = curl_exec($curl);
    curl_close($curl);

    $json = json_decode($outPut,true);
    if($json){
        return $json;
    }else{
        libxml_disable_entity_loader(true);
        $xml = simplexml_load_string($outPut,'SimpleXMLElement',LIBXML_NOCDATA);
        return $xml;
    }
}

/**
 * 无限极分类
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 */
function make_tree($list,$pk='id',$pid='parent',$child='_child',$root=0){
    $tree=array();
    $packData=array();
    foreach ($list as  $data) {
        $packData[$data[$pk]] = $data;
    }
    foreach ($packData as $key =>$val){
        if($val[$pid]==$root){//代表跟节点
            $tree[]=& $packData[$key];
        }else{
            //找到其父类
            $packData[$val[$pid]][$child][]=& $packData[$key];
        }
    }
    return $tree;
}
// 获取课程分类名称
function category_name($id){
    $category = [
        '1' => '数学',
        '2' => '逻辑',
        '3' => '作文',
        '4' => '英语',
        '5' => '组合',
        '6' => '电子书',
        '7' => '综合'
    ];
    if(isset($category[$id])){
        return $category[$id];
    }
    return '';
}

// 获取学历分类名称
function education_name($id){
    $education = [
        '1' => '专科',
        '2' => '本科',
        '3' => '硕士',
        '4' => '博士'
    ];
    if(isset($education[$id])){
        return $education[$id];
    }
    return '';
}

// 获取地区名称
function area_name($id){
    $name = db('areas')->where('area_id',$id)->find();
    if($name){
        return $name['area_name'];
    }
    return '';
}

// 获取教师信息
function teacher_info($str){
    $teachers = [];
    if(trim($str,',')){
        $teachers = \think\Db::name('teacher')->field('status,create_time,update_time',true)->where('status','eq',1)->where('id','in',$str)->select();
        if(!empty($teachers)){
            foreach ($teachers as &$value){
                $value['education'] = json_decode($value['education']);
            }
        }
    }
    return $teachers;
}

// 判断是否已购买
function check_buy($uid,$course_id){
    $order = \think\Db::name('course_order')->where('user_id',$uid)->where('course_id',$course_id)->where('status',1)->find();
    if($order){
        // 订单有效期一年
        $time = strtotime($order['create_time'])+31536000;
        if(time() < $time){
            return true;
        }
    }
    return false;
}
// 获取唯一订单号 1-充值订单，2-购买订单
function order_no($type)
{
    $out_trade_no = date("YmdHis", time()) . rand(111111, 999999);
    if($type == 1){
        $list = \think\Db::name('pay_records')->where(['trade_number'=>$out_trade_no])->find();
    }else{
        $list = \think\Db::name('course_order')->where(['trade_number'=>$out_trade_no])->find();
    }

    if (empty($list)) {
        return $out_trade_no;
    } else {
        return order_no($type);
    }
//    return $out_trade_no;
}

// 根据日期返回年龄
function birthday($birthday){
    $age = strtotime($birthday);
    if($age === false){
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
    $mail = new \PHPMailer();           //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';          // 使用安全协议
    $mail->Host = "smtp.163.com"; // SMTP 服务器
    $mail->Port = 465;                  // SMTP服务器的端口号
    $mail->Username = "haibinketang@163.com";    // SMTP服务器用户名
    $mail->Password = "haibinluoji1405";     // SMTP服务器密码
    $mail->SetFrom('haibinketang@163.com', '海滨课堂');
    $replyEmail = '';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
//    if (is_array($attachment)) { // 添加附件
//        foreach ($attachment as $file) {
//            is_file($file) && $mail->AddAttachment($file);
//        }
//    }
    if($attachment){
        $mail->AddAttachment($attachment);
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

function mail_content($title,$price,$content,$file_url){
    $html = '
<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{
				padding: 0;
				margin:0;
			}
			#email{
				margin: 0 auto;
				width:800px;
				height:900px;
				
				border:1px solid #e0e0e0;
			}
			p{font-size:14px;}
			#email h5{
				height:80px;
				background: #f5f5f5;
				font-size:25px;
				color:#656567;
				line-height:80px;
				text-indent: 10px;
			}
			
			#dear{
				padding-left:19px;
				height:80px;
				font-size:20px;
				line-height:80px;
				color:#19a3eb;
			}
			#true{
				padding-left:19px;
				color:#323232;
				padding-bottom: 37px;
			}
			#content{
				padding:0 19px 35px 19px;
				line-height:26px;
				color:#656565;
				font-size: 14px;
			}
			#text{
				padding-left:19px;
				color:#333333;
				padding-bottom:13px;
				
			}
			#lianjie{
				display: block;
				padding:0 0 34px 19px;
				color:#055594;
			}
			.hope{
				padding:0 0 10px 19px;
				color:#666666;
				font-size: 14px;
				
			}
		</style>
	</head>
	<body>
		<div id="email">
			<h5>海滨课堂</h5>
			<p id="dear">亲爱的用户，您好：</p>
			<p id="true">您已成功购买《'.$title.'》，价格<span>'.$price.'</span>研币。</p>
			<p id="content">'.$content.'</p>
		    <p id="text">电子资料下载链接如下：</p>
		    <a id="lianjie" href="'.$file_url.'">点击此处进行下载</a>
		    <p class="hope">
		    	希望您再次购买我们的商品，我们会全心全意为备考生服务，如果有更好的建议，请您和我们联系。
		    	
		    </p>
		     <p class="hope">
		     	我们的客服QQ为：3526747829，欢迎提出您的意见和建议，感谢你的支持。
		     </p>
		    
		</div>
	</body>
</html>
';
    return $html;
}

/*
 * 获取随机红包
 * min<k<max
 * min(n-1) <= money - k <= (n-1)max
 * k <= money-(n-1)min
 * k >= money-(n-1)max
 */
function getRedPackage($money, $num, $min, $max)
{
    $data = array();
    if ($min * $num > $money) {
        return array();
    }
    if($max*$num < $money){
        return array();
    }
    while ($num >= 1) {
        $num--;
        $kmix = max($min, $money - $num * $max);
        $kmax = min($max, $money - $num * $min);
        $kAvg = $money / ($num + 1);
        //获取最大值和最小值的距离之间的最小值
        $kDis = min($kAvg - $kmix, $kmax - $kAvg);
        //获取0到1之间的随机数与距离最小值相乘得出浮动区间，这使得浮动区间不会超出范围
        $r = ((float)(rand(1, 10000) / 10000) - 0.5) * $kDis * 2;
        $k = round($kAvg + $r);
        $money -= $k;
        $data[] = $k;
    }
    return $data;
}

// 获取分类名称
function get_sort_name($platform,$cat){
    $map['cat'] = $cat;
    $map['platform'] = $platform;
    $str = \think\Db::name('sort')->field('name')->where($map)->find();
    if(!empty($str)){
        return $str['name'];
    }
    return '';
}

function map_sort($id){
    $array = [
        '1'=>'全部',
        '2'=> '汽车',
        '3'=> '动漫',
        '4'=> '亲子',
        '5'=> '财经',
        '6'=> '娱乐',
        '7'=> '时尚',
        '8'=> '美食',
        '9'=>'搞笑',
        '10'=> '游戏',
        '11'=>'健康',
        '12'=> '资讯',
        '13'=> '知识',
        '14'=> '生活',
        '15'=> '音乐',
        '16'=> '萌宠',
        '17'=> '运动',
        '18'=> '科技',
        '19'=> '旅游'
    ];
    if(array_key_exists($id,$array)){
        return $array[$id];
    }
    return true;
}

// 单位转换
function get_size($size,$format = 'kb'){
    $p = 0;
    if($format == 'kb'){
        $p = 1;
    }else if($format == 'mb'){
        $p = 2;
    }else if($format == 'gb'){
        $p = 3;
    }
    $size /= pow(1024,$p);
    return number_format($size,3);
}